package com.ycb.lock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author 黄泽群
 * @since 2024-01-03
 */
@Slf4j
public class SemaphoreApp {

    public static void main(String[] args) throws Exception {
        int count  = 5;
        log.info("init");
        CountDownLatch countDownLatch = new CountDownLatch(count);
        Semaphore semaphore = new Semaphore(2);
        for (int i = 0; i < count; i++) {
            new Thread(){
                @Override
                public void run() {
                    log.info("  execute ");
                    boolean tryAcquire = semaphore.tryAcquire();
                    log.info("  tryAcquire : {} ",tryAcquire);
                    if (tryAcquire) {
                        try {
                            TimeUnit.SECONDS.sleep(1L);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                        log.info("  release  ");
                        semaphore.release();
                    }
                    log.info(" Thread Exit  ");
                    countDownLatch.countDown();
                }
            }.start();
        }
        countDownLatch.await();
        log.info("exit");
    }

}
